import { createRouter, createWebHistory } from 'vue-router'

// Import the layout component
import MainLayout from '../layouts/MainLayout.vue'

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/login',
      name: 'login',
      component: () => import('../views/Login.vue'),
      meta: {
        title: '登录',
        requiresAuth: false
      }
    },
    {
      path: '/',
      component: MainLayout,
      meta: {
        requiresAuth: true
      },
      children: [
        {
          path: '',
          name: 'home',
          component: () => import('../views/Home.vue')
        },
        {
          path: 'water-quality/device',
          name: 'device',
          component: () => import('../views/water-quality/device/index.vue'),
          meta: {
            title: '设备管理',
            icon: 'Monitor'
          }
        },
        {
          path: 'water-quality/visualization',
          name: 'visualization',
          component: () => import('../views/water-quality/visualization/index.vue'),
          meta: {
            title: '可视化界面',
            icon: 'DataLine'
          }
        },
        {
          path: 'water-quality/system',
          name: 'system',
          component: () => import('../views/water-quality/system/index.vue'),
          meta: {
            title: '系统管理',
            icon: 'Setting',
            keepAlive: false
          }
        }
      ]
    }
  ],
})

// 路由守卫
router.beforeEach((to, from, next) => {
  console.log('路由跳转:', from.path, '->', to.path)
  console.log('目标组件:', to.name)
  console.log('目标meta:', to.meta)
  
  // 检查是否需要登录验证
  if (to.meta.requiresAuth) {
    const userInfo = localStorage.getItem('userInfo') || sessionStorage.getItem('userInfo')
    if (!userInfo) {
      // 未登录，跳转到登录页
      console.log('未登录，跳转到登录页')
      next('/login')
      return
    }
  }
  
  // 如果已登录且访问登录页，跳转到首页
  if (to.path === '/login') {
    const userInfo = localStorage.getItem('userInfo') || sessionStorage.getItem('userInfo')
    if (userInfo) {
      console.log('已登录，跳转到首页')
      next('/')
      return
    }
  }
  
  console.log('路由守卫通过，继续导航')
  next()
})

// 路由后置守卫
router.afterEach((to, from) => {
  console.log('路由跳转完成:', from.path, '->', to.path)
  console.log('当前组件:', to.name)
})

export default router